package com.gjy.mybatis.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-10-28 18:16:46
 */
public class MapTypeHandler implements TypeHandler<MapEntity> {

    private static final ObjectMapper OM = new ObjectMapper();

    @Override
    public void setParameter(PreparedStatement ps, int i, MapEntity parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.getOrigin());
    }

    @Override
    public MapEntity getResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return getMap(value);
    }

    @Override
    public MapEntity getResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return getMap(value);
    }

    @Override
    public MapEntity getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return getMap(value);
    }

    private static MapEntity getMap(String value) {
        try {
            Map<String, Object> map = OM.readValue(value, new TypeReference<Map<String, Object>>() {
            });
            return new MapEntity(map);
        } catch (JsonProcessingException e) {
            MapEntity map = new MapEntity();
            map.setError(e.getMessage());
            return map;
        }
    }

}
